package antidestiny.utilib.io;

import android.content.res.AssetManager;
import android.text.TextUtils;

import java.io.IOException;
import java.util.ArrayList;

/**用于读取assets文件夹下的文件
 * Created by Hero on 2016/7/23.
 */
public class AssetUtils {
    public static boolean isDir(String path,AssetManager manager)throws IOException {
        return manager.list(path).length != 0;
    }

    /**
     * 返回assets某个路径之后的所有文件，不含文件夹
     * 文件很多时耗时很久
     * @param path
     * @param manager
     * @return
     * @throws IOException
     */
    public static ArrayList<String> getAllFile(String path,AssetManager manager)throws IOException{
        ArrayList<String> files=new ArrayList<>();
        path=formatPath(path);
        String[] paths=manager.list(path);
        for (String p:paths){
            if (path.length()!=0)
                p=formatPath(path+"/"+p);
            if (isDir(p,manager)){
                files.addAll(getAllFile(p,manager));
            }else {
                files.add(p);
            }
        }
        return files;

    }

    /**
     * 以下的路径不合法：
     * /path
     * path/
     * /path/
     * 正确的路径是：
     * path
     * 此函数可以删去不必要的‘/’
     * @param path
     * @return
     */
    public static String formatPath(String path){
        while (path.startsWith("/"))
            path=path.substring(1);
        while (path.endsWith("/"))
            path=path.substring(0,path.length()-1);
        return path;
    }

    public static boolean exists(String path,AssetManager manager) throws IOException{
        TextUtils.SimpleStringSplitter splitter=new TextUtils.SimpleStringSplitter('/');
        splitter.setString(path);
        String dir="";
        FIRST: while(splitter.hasNext()){
            String[] files=manager.list(dir);
            String next=splitter.next();
            dir=dir+(dir.length()==0?"":'/')+next;
            for (String file:files){
                 if (file.equals(next))
                    continue FIRST;
            }
            return false;
        }
        return true;
    }
}
